package com.xci.platform.auth.api;

import com.xci.platform.auth.core.AuthHelper;
import com.xci.platform.auth.entity.LogEntity;
import com.xci.platform.auth.entity.UserEntity;
import com.xci.platform.auth.service.LogService;
import com.xci.platform.auth.service.UserService;
import com.xci.platform.annotation.AllowAnonymous;
import com.xci.platform.annotation.Authorize;
import com.xci.platform.core.BoolMessage;
import com.xci.platform.helper.DateHelper;
import com.xci.platform.helper.TokenHelper;
import com.xci.platform.helper.CoreHelper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;

@Slf4j
@Authorize
@RestController
@RequestMapping("/api/auth/system")
public class SystemApiController {

    /**
     * 用户服务
     */
    @Resource
    private UserService userService;

    /**
     * 日志服务
     */
    @Resource
    private LogService logService;

    @AllowAnonymous
    @PostMapping("/token")
    public BoolMessage token(String appId) {
        return new BoolMessage<>(true, "ok", TokenHelper.createJwtToken(appId));
    }

    @AllowAnonymous
    @GetMapping("/systemDatetime")
    public String systemDatetime() {
        return DateHelper.formatDateTime(new Date());
    }

    @AllowAnonymous
    @PostMapping("/login")
    public BoolMessage login(String account, String password, String captcha, HttpServletRequest request) {
        long startTime = CoreHelper.startWatch();
        BoolMessage<UserEntity> result = userService.login(account, password);
        if (result.isSuccess()) {
            //添加登录审计日志
            LogEntity logEntity = AuthHelper.buildAuditInfo(request, "登录成功", CoreHelper.stopWatch(startTime));
            logService.insert(logEntity);
            return BoolMessage.True;
        }
        return result;
    }
}
